System.Array.BinarySearch 方法 (T[], T)

方法描述

使用由 Array 中每个元素和指定的对象实现的 IComparable 泛型接口,在整个一维排序 Array 中搜索特定元素。

语法定义(C# System.Array.BinarySearch 方法 (T[], T) 的用法)

public static int BinarySearch(
	T[] array,
	T value
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
array T[] 要搜索的从零开始的一维排序 Array。
value T 要搜索的对象。
返回值 System.Int32 如果找到 value,则为指定 array 中的指定 value 的索引。 如果找不到 value 且 value 小于 array 中的一个或多个元素,则为一个负数,该负数是大于 value 的第一个元素的索引的按位求补。 如果找不到 value 且 value 大于 array 中的任何元素,则为一个负数,该负数是(最后一个元素的索引加 1)的按位求补。

提示和注释

此方法不支持搜索包含负索引的数组。 调用此方法前,必须对数组进行排序。

如果 Array 不包含指定值,则该方法会返回负整数。 可对负结果应用按位求补运算符 (~)(在 Visual Basic 中,将负结果和 -1 进行 Xor 运算)以生成一个索引。 如果此索引大于等于数组的大小,则数组中没有比 value 更大的元素。 否则,即为大于 value 的第一个元素的索引。

value 或 array 的每个元素都必须实现 IComparable 泛型接口,该接口用于进行比较。 array 的元素必须已经根据 IComparable 实现定义的排序顺序按升序排序;否则,结果可能不正确。

注意

如果 value 没有实现 IComparable 泛型接口,则在搜索开始前不会针对 IComparable 测试 array 的元素。 如果搜索时遇到没有实现 IComparable 的元素,将引发异常。

允许重复元素。 如果 Array 包含多个值等于 value 的元素,则该方法将仅返回一个匹配项(不一定是第一个匹配项)的索引。

null 总是可以与任何其他引用类型比较,因此与 null 的比较不会产生异常。 排序时,null 被视为小于任何其他对象。

注意

对于每个进行测试的元素,都将 value 传递给相应的 IComparable 实现,即使 value 为 null 也一样。 即,IComparable 实现确定一个给定的元素如何与 null 进行比较。

此方法的运算复杂度为 O(log n),其中 n 是 array 的 Length。

System.Array.BinarySearch 方法 (T[], T)例子

如果字符串不在数组中,则索引为负,因此 ShowWhere 方法会采用按位求补(在 C# 和 Visual C++ 中使用 ~ 运算符,在 Visual Basic 中使用 Xor -1),以获得列表中大于搜索字符串的第一个元素的索引。

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus", 
                              "Amargasaurus", 
                              "Tyrannosaurus", 
                              "Mamenchisaurus", 
                              "Deinonychus", 
                              "Edmontosaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nSort");
        Array.Sort(dinosaurs);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch for 'Coelophysis':");
        int index = Array.BinarySearch(dinosaurs, "Coelophysis");
        ShowWhere(dinosaurs, index);

        Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus");
        ShowWhere(dinosaurs, index);
    }

    private static void ShowWhere(T[] array, int index)
    {
        if (index<0)
        {
            // If the index is negative, it represents the bitwise
            // complement of the next larger element in the array.
            //
            index = ~index;

            Console.Write("Not found. Sorts between: ");

            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index-1]);

            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Amargasaurus and Deinonychus.

BinarySearch for 'Tyrannosaurus':
Found at index 5.
 */

异常

异常 异常描述
ArgumentNullException array 为 null。
InvalidOperationException value 没有实现 IComparable 泛型接口,并且搜索时遇到没有实现 IComparable 泛型接口的元素。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。